package tech.popsoft.cip.manage.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import tech.popsoft.cip.manage.service.ApiServiceService;
import tech.popsoft.cip.manage.vo.ApiServiceVO;
import tech.popsoft.platform.common.base.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import tech.popsoft.platform.common.annotation.SystemLog;
import tech.popsoft.platform.common.query.QueryGenerator;
import tech.popsoft.platform.common.utils.ResultUtil;
import tech.popsoft.platform.common.vo.PageInfo;
import tech.popsoft.platform.common.vo.Result;
import tech.popsoft.platform.common.vo.SortInfo;
import tech.popsoft.cip.manage.entity.ApiService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 接口服务 前端控制器
 * @author wqliu
 * @date 2021-08-17
 *
 */
@RestController
@RequestMapping("/cip/apiService")
@Slf4j
public class ApiServiceController extends BaseController {
 @Autowired
 private ApiServiceService apiServiceService;

    //region 基本操作
    /**
     * 初始化
     */
    @ApiOperation(value = "初始化")
    @GetMapping("/init")
    public ResponseEntity<Result> init() {
        ApiService entity=apiServiceService.init();
        ApiServiceVO vo = convert2VO(entity);
        return ResultUtil.success(vo);
    }

    /**
     * 新增
     */
    @ApiOperation(value = "新增")
    @PostMapping("/")
    @SystemLog(value = "接口服务-新增")
    @PreAuthorize("hasPermission(null,'cip:apiService:add')")
    public ResponseEntity<Result> add(@Validated @RequestBody ApiServiceVO vo) {
        ApiService entity=convert2Entity(vo);
        apiServiceService.add(entity);
        ApiServiceVO newVO = convert2VO(entity);
        return ResultUtil.success(newVO);
    }

    /**
     * 修改
     */
    @ApiOperation(value = "修改")
    @PutMapping("/")
    @SystemLog(value = "接口服务-修改")
    @PreAuthorize("hasPermission(null,'cip:apiService:modify')")
    public ResponseEntity<Result> modify(@Validated @RequestBody ApiServiceVO vo)  {
        ApiService entity=convert2Entity(vo);
        //此处数据库会更新 更新人和更新时间，但数据模型不会刷新
        //个别需展示的该类信息的地方可以重新查询后返回
        apiServiceService.modify(entity);
        ApiServiceVO newVO = convert2VO(entity);
        return ResultUtil.success(newVO);
    }

    /**
     * 删除数据，单条数据标识，或多条数据标识用逗号间隔拼成的字符串
     */
    @ApiOperation(value = "删除")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String",paramType ="path")
    @DeleteMapping("/{id}")
    @SystemLog(value = "接口服务-删除")
    @PreAuthorize("hasPermission(null,'cip:apiService:remove')")
    public ResponseEntity<Result> remove(@PathVariable("id") String id) {
        apiServiceService.remove(id);
        return ResultUtil.success();
    }

    /**
     * 分页
     */
    @ApiOperation(value = "分页查询")
    @GetMapping("/page")
    @SystemLog(value = "接口服务-分页")
    @PreAuthorize("hasPermission(null,'cip:apiService:query')")
    public ResponseEntity<Result> page(ApiServiceVO queryVO, PageInfo pageInfo, SortInfo sortInfo) {

        //构造分页对象
        IPage<ApiService> page = new Page<ApiService>(pageInfo.getPageNum(), pageInfo.getPageSize());
        //构造查询条件
        QueryWrapper<ApiService> queryWrapper = QueryGenerator.generateQueryWrapper(ApiService.class,queryVO,sortInfo);

        //查询数据
        apiServiceService.page(page, queryWrapper);
        //转换vo
        IPage<ApiServiceVO> pageVO = mapperFacade.map(page, IPage.class);
        List<ApiServiceVO>  apiServiceVOList=new ArrayList<>();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ApiServiceVO vo = convert2VO(page.getRecords().get(i));
            apiServiceVOList.add(vo);
        }
        pageVO.setRecords(apiServiceVOList);        ;
        return ResultUtil.success(pageVO);
    }


    /**
     * 列表
     */
    @ApiOperation(value = "获取列表")
    @GetMapping("/list")
    @SystemLog(value = "接口服务-列表")
    @PreAuthorize("hasPermission(null,'cip:apiService:query')")
    public ResponseEntity<Result> list(ApiServiceVO queryVO, SortInfo sortInfo) {
        //构造查询条件
        QueryWrapper<ApiService> queryWrapper = QueryGenerator.generateQueryWrapper(ApiService.class, queryVO,sortInfo);
        List<ApiService> list= apiServiceService.list(queryWrapper);
        //转换vo
        List<ApiServiceVO>  apiServiceVOList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ApiServiceVO vo = convert2VO(list.get(i));
            apiServiceVOList.add(vo);
        }
        return ResultUtil.success(apiServiceVOList);
    }

    /**
     * 获取单条数据
     */
    @ApiOperation(value = "获取单条数据")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String",paramType ="path")
    @GetMapping("/{id}")
    @SystemLog(value = "接口服务-详情")
    @PreAuthorize("hasPermission(null,'cip:apiService:view')")
    public ResponseEntity<Result> get(@PathVariable("id") String id) {
        ApiService entity = apiServiceService.query(id);
        ApiServiceVO vo = convert2VO(entity);
        return ResultUtil.success(vo);
    }

    //endregion

    //region 扩展操作
    /**
     * 启用
     */
    @ApiOperation(value = "启用")
    @PutMapping("/{id}/enable")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String", paramType = "path")
    @SystemLog(value = "接口服务-启用")
    @PreAuthorize("hasPermission(null,'cip:apiService:enable')")
    public ResponseEntity<Result> enable(@PathVariable("id") String id) {

        apiServiceService.enable(id);
        return ResultUtil.success();
    }

    /**
     * 停用
     */
    @ApiOperation(value = "停用")
    @PutMapping("/{id}/disable")
    @ApiImplicitParam(name = "id", value = "标识", required = true, dataType = "String", paramType = "path")
    @SystemLog(value = "接口服务-停用")
    @PreAuthorize("hasPermission(null,'cip:apiService:disable')")
    public ResponseEntity<Result> disable(@PathVariable("id") String id) {

        apiServiceService.disable(id);
        return ResultUtil.success();
    }

    /**
     * 接口服务权限查询
     */
    @GetMapping("/queryApiPermission")
    @SystemLog(value = "接口服务-查询指定应用服务权限")
    @PreAuthorize("hasPermission(null,'cip:apiApp:grantApiPermission')")
    public ResponseEntity<Result> queryApiPermission(ApiServiceVO queryVO, SortInfo sortInfo) {
        //暂存传入的参数
        String appId=queryVO.getAppId();
        String hasPermission = queryVO.getHasPermission();
        //移除hasPermission参数，否则会构建sql语句，而该字段并不存在
        queryVO.setHasPermission(null);
        //构造查询条件
        QueryWrapper<ApiService> queryWrapper = QueryGenerator.generateQueryWrapper(ApiService.class, queryVO,sortInfo);
        List<ApiService> list= apiServiceService.queryApiPermission(queryWrapper,appId,hasPermission);
        //转换vo
        List<ApiServiceVO>  apiServiceVOList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ApiServiceVO vo = convert2VO(list.get(i));
            apiServiceVOList.add(vo);
        }
        return ResultUtil.success(apiServiceVOList);
    }


    //endregion

    //region 辅助操作

    private ApiServiceVO convert2VO(ApiService entity){
        ApiServiceVO vo=mapperFacade.map(entity,ApiServiceVO.class);
        String statusName = dictionaryUtil.getNameByCode("Status", entity.getStatus());
        vo.setStatusName(statusName);
        String categoryName = dictionaryUtil.getNameByCode("ApiServiceCategory", entity.getCategory());
        vo.setCategoryName(categoryName);

        if(StringUtils.isNotBlank(entity.getHasPermission())){
            String hasPermission = dictionaryUtil.getNameByCode("YesOrNo", entity.getHasPermission());
            vo.setHasPermissionName(hasPermission);
        }

        return vo;
    }

    private ApiService convert2Entity(ApiServiceVO vo){

        ApiService entity=mapperFacade.map(vo,ApiService.class);
        return entity;
    }

   //endregion
}
